﻿using Core;
using FairyGUI;
using UnityEngine;

public class DescribeWidget : FGUIWidget<Widget.UI_Describe>
{
    public void ShowItemInfo(int itemId, Vector2 position)
    {
        var config = World.GetComponent<ConfigComponent>().GetConfig<ItemConfig>(itemId);
        if (config == null)
            return;

        m_root.m_name.text = World.GetComponent<LangComponent>().Get(config.name);
        m_root.m_des.text = World.GetComponent<LangComponent>().Get(config.des);

        m_root.position = position;
        Show();
    }

    public void ShowItemInfo(int itemId, GObject component)
    {
        var config = World.GetComponent<ConfigComponent>().GetConfig<ItemConfig>(itemId);
        if (config == null)
            return;

        m_root.m_name.text = config.name;
        m_root.m_des.text = config.des;

        UpdatePosition(component);
        Show();

    }

    private void UpdatePosition(GObject component)
    {
        m_root.EnsureBoundsCorrect();

        var position = component.LocalToGlobal(Vector2.zero);
        var width = GRoot.inst.width;
        var height = GRoot.inst.height;

        var pos = default(Vector2);
        pos.Set(position.x - (m_root.width - component.width) / 2, position.y - m_root.height);

        bool isChangeMode = false;

        if (pos.x < 0)
        {
            pos.x = position.x;
        }
        else if (pos.x + m_root.width > width)
        {
            isChangeMode = true;
        }

        if(pos.y < 0)
        {
            isChangeMode = true;
        }

        if (isChangeMode)
        {
            pos.x = position.x < width / 2 ? position.x + component.width : position.x - m_root.width;
            pos.y = position.y - Mathf.Max(0, position.y + m_root.height - height);

            if(pos.y < 0)
            {
                pos.y = 0;
            }
        }

        m_root.position = pos;

    }
}